﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using TruyenCuoiViet.ViewModels;
using TruyenCuoiViet.Source.Helper;
using Microsoft.Phone.Tasks;

namespace TruyenCuoiViet.Source.UI
{
    public partial class MainPage : PhoneApplicationPage
    {
        public static MainPage instance;
        public int currentcategory = 0;
        // Constructor
        public MainPage()
        {
            instance = this;
            InitializeComponent();
            DataContext = App.ViewModel;

        }

        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            prbLoad.Visibility = Visibility.Collapsed;
            if (NavigationContext.QueryString.ContainsKey("q"))
            {
                CategoryViewModel vm= App.ViewModel.FindCategory(6);
                vm.Page = 1;
                vm.KeyWord = NavigationContext.QueryString["q"];
                vm.IsDataLoaded = false;
            }
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData(currentcategory);
            }
            if (NavigationContext.QueryString.ContainsKey("CategoryId"))
            {
                int c = int.Parse(NavigationContext.QueryString["CategoryId"]);
                pvDanTri.SelectedItem = App.ViewModel.FindCategory(c);
            }           
        }

        private void pvDanTri_LoadedPivotItem(object sender, PivotItemEventArgs e)
        {
            CategoryViewModel c = pvDanTri.SelectedItem as CategoryViewModel;
            currentcategory = c.Id;
            c.Loaddata();
        }

        private void Grid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string id = ((sender as Grid).FindName("tblId") as TextBlock).Text;
            NavigationService.Navigate(new Uri("/Source/UI/ReadNews.xaml?NewsId=" + id + "&CategoryId=" + currentcategory, UriKind.Relative));
        }

        private void btnNext_Click(object sender, System.EventArgs e)
        {
            CategoryViewModel c = pvDanTri.SelectedItem as CategoryViewModel;
            c.Next();
            ScrollToTop();
        }
        private void ScrollToTop()
        {
            PivotItem pvitem = pvDanTri.ItemContainerGenerator.ContainerFromItem(pvDanTri.SelectedItem) as PivotItem;
            ScrollViewer sc = FindScrollViewer(pvitem);
            sc.ScrollToVerticalOffset(0);
        }
        private ScrollViewer FindScrollViewer(DependencyObject parent)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var _Child = VisualTreeHelper.GetChild(parent, i);
                if (_Child is ScrollViewer)
                {
                    return _Child as ScrollViewer;
                }
                return FindScrollViewer(_Child);
            }
            return null;
        } 
        private void btnPrev_Click(object sender, System.EventArgs e)
        {
            CategoryViewModel c = pvDanTri.SelectedItem as CategoryViewModel;
            c.Prev();
            ScrollToTop();
        }

        private void btnRefresh_Click(object sender, System.EventArgs e)
        {
            CategoryViewModel ct = pvDanTri.SelectedItem as CategoryViewModel;
            ct.ReLoadData();
            ScrollToTop();
        }

        private void btnCategory_Click(object sender, System.EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Source/UI/Selectcategory.xaml?CategoryId=" + currentcategory, UriKind.Relative));
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("Bạn có chắc chắn muốn thoát ứng dụng ?", "Thoát !", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                NavigationService.Navigate(new Uri("/Source/UI/AdPage.xaml?Exit=1", UriKind.Relative));
            }
            else
            {
                e.Cancel = true;
            }
        }
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            PhoneApplicationPage phoneApplicationPage = (PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content;
            TransitionHelper.excuteTransition(phoneApplicationPage);
            base.OnNavigatingFrom(e);
        }

        private void mnGotoPage_Click(object sender, EventArgs e)
        {
            var tb = new TextBox();
            var box = new CustomMessageBox()
            {
                Caption = "Chuyển đến trang",
                Message = "Hãy nhập số của trang muốn chuyển đến",
                LeftButtonContent = "Đến",
                RightButtonContent = "Hủy",
                Content = tb,
                IsFullScreen = false
            };
            box.Dismissed += (s, e1) =>
            {
                if (e1.Result == CustomMessageBoxResult.LeftButton)
                {
                    var filename = tb.Text;
                    int page;
                    if(int.TryParse(filename,out page))
                    {
                        CategoryViewModel c = pvDanTri.SelectedItem as CategoryViewModel;
                        c.GotoPage(page);
                        ScrollToTop();
                    }
                    else
                    {
                        MessageBox.Show("Bạn phải nhập vào số");
                    }
                }
            };
            box.Show();
        }

        private void mnRate_Click(object sender, EventArgs e)
        {
            MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
            marketplaceReviewTask.Show();
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            CategoryViewModel vm=App.ViewModel.FindCategory(6);
            vm.KeyWord = ((((Button)sender).Parent as Grid).FindName("txtSearch") as TextBox).Text;
            vm.Page = 1;
            pvDanTri.SelectedItem = vm;
            btnRefresh_Click(null, null);
        }
    }
}